package badugi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * Manages communication with one client.
 * Created by grzegorz on 10/14/14.
 */
public class PlayerWorker implements Runnable {
	private Socket client;
	private PrintStream out;
	private BufferedReader in;
	private final Table table;
	private int id;
	private final Server server;

	public int getID() {
		return id;
	}

	public PrintStream getOut() {
		return out;
	}

	public Socket getClient() {
		return client;
	}

	public PlayerWorker( Server server, Socket player, Table table, int id ) {
		this.server = server;
		this.client = player;
		this.table = table;
		this.id = id;
		System.out.println( "Connected." );
		try {
			out = new PrintStream( this.client.getOutputStream(), true );
			out.println( id );
			out.println( table.getSmallBlind() );
			out.println( table.getBigBlind() );
			out.println( table.getChips() );
		}
		catch( IOException e ) {
			System.out.println( "I/O error.");
		}
		catch( NullPointerException e ) {
			System.out.println( "NullPointerException." );
		}
	}

	private void close() {
		server.playerDisconnected( this );
		try {
			if( out != null )
				out.close();
			if( in != null )
				in.close();
			if( client != null )
				client.close();
			out = null;
			in = null;
			client = null;
		}
		catch( IOException e ) {
			System.out.println( "Closing failed." );
		}
	}

	@Override
	protected void finalize() throws Throwable {
		close();
		super.finalize();
	}

	@Override
	public void run() {
		String message;
		try {
			in = new BufferedReader( new InputStreamReader( client.getInputStream() ) );
			out = new PrintStream( client.getOutputStream(), true );
			while( in != null && ( message = in.readLine() ) != null ) {
				if( message.equals( "Q" ) ) {
					System.out.println( "QUIT" );
					table.receiveMessage( message, id );
					close();
				}
				if( message.length() >= 1 ) {
					System.out.println( message + " " + id );
					table.receiveMessage( message, id );
				}
				else
					System.out.println( "Wrong message in Worker." );
			}
		}
		catch( IOException e ) {
			System.out.println( "I/O error.   " + e.getMessage() );
			System.exit( 1 );
		}
	}
}